package com.nanfang51g3.ckz.ui.login;

import android.content.Context;
import android.text.TextUtils;

import com.nanfang51g3.ckz.di.ApiModule;
import com.nanfang51g3.ckz.domain.HttpResultBean;
import com.nanfang51g3.ckz.domain.UserBean;
import com.nanfang51g3.ckz.exec.Api2Exception;
import com.nanfang51g3.ckz.http.HttpResultFunc;
import com.nanfang51g3.ckz.http.RestApi;
import com.nanfang51g3.ckz.http.SubscriberInterface;
import com.nanfang51g3.ckz.utils.KLog;
import com.nanfang51g3.ckz.utils.MD5Utils;
import com.nanfang51g3.ckz.utils.SPUtil;

import java.util.TreeMap;

import javax.inject.Inject;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2016/4/13.
 */
public class LoginPresenter implements LoginContract.LoginActionsListener {

    String message;
    private final RestApi _restApi;
    private final LoginContract.View mView;
    /**
     * @see ApiModule#provideRetrofit()
     */
    @Inject
    Retrofit retrofit;

    @Inject
    public LoginPresenter(RestApi restApi, LoginContract.View mView) {
        KLog.i("TAG", "进入了...LoginPresenter");
        /**
         * @see ApiModule#provideRestApi(Retrofit)
         */
        this._restApi = restApi;
        KLog.i("TAG", _restApi == null ? "进入了...is null" : "进入了...not null");
        /**
         * @see LoginPresenterModule#LoginPresenterModule(LoginContract.View)
         */
        this.mView = mView;
        KLog.i("TAG", mView == null ? "进入了...is null" : "进入了...not null");
    }

    @Override
    public void login(String u, final String p) {
        KLog.i("TAG", retrofit == null ? "retrofit-1" : "retrofit-0");
        TreeMap<String, String> treeMap = new TreeMap<>();
        treeMap.put("phone", u);
        treeMap.put("password", p);
        String sign = MD5Utils.getAccessToken(treeMap);
        KLog.e("Evd", sign);
        Observable observable = _restApi.login(u, p, sign);
        observable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .map(new LoginResultFunc<UserBean>())

                .subscribe(new SubscriberInterface<UserBean>() {


                    /**
                     * 订阅开始时调用
                     */
                    @Override
                    public void onStart() {
                        super.onStart();
                        KLog.i("Evd", "onStart");
                        /**
                         * @see LoginActivity#showProgress()
                         */
                        mView.showProgress();
                    }

                    /**
                     * 请求完成
                     */
                    @Override
                    public void onCompleted() {
                        KLog.i("Evd", "onCompleted");
                        /**
                         * @see LoginActivity#dismissProgress()
                         */
                        mView.dismissProgress();
                    }

                    @Override
                    public void _onError(String msg) {
                        KLog.i("Evd", "Throwable " + msg);
//                        Throwable java.net.ConnectException: Failed to connect to /192.168.2.138:80
                        /**
                         * @see  LoginActivity#showMessage(String)
                         */
                        mView.showMessage(msg);
                        /**
                         * @see  LoginActivity#dismissProgress()
                         */
                        mView.dismissProgress();
                    }


                    /**
                     * 数据
                     *
                     * @param o
                     */
                    @Override
                    public void onNext(UserBean o) {
                        KLog.i("Evd", "onNext " + o.toString());
                        Context context = mView.getContext();
                        SPUtil.putAndApply(context, "is_login", true);
                        SPUtil.putAndApply(context, "userid", o.getUserid());
                        SPUtil.putAndApply(context, "phone", o.getPhone());
                        SPUtil.putAndApply(context, "password", p);
                        SPUtil.putAndApply(context, "username", TextUtils.isEmpty(o.getUsername()) ? "暂未填写" : o.getUsername());
                        SPUtil.putAndApply(context, "real_name", TextUtils.isEmpty(o.getReal_name()) ? "暂未填写" : o.getReal_name());
                        SPUtil.putAndApply(context, "userpic", TextUtils.isEmpty(o.getUserpic()) ? "暂未填写" : o.getUserpic());
                        SPUtil.putAndApply(context, "email", TextUtils.isEmpty(o.getEmail()) ? "暂未填写" : o.getEmail());
                        SPUtil.putAndApply(context, "qq", TextUtils.isEmpty(o.getQq()) ? "暂未填写" : o.getQq());
                        SPUtil.putAndApply(context, "ali_pay_card", TextUtils.isEmpty(o.getAlipay()) ? "暂未填写" : o.getAlipay());
                        SPUtil.putAndApply(context, "bank_card", TextUtils.isEmpty(o.getBank_card()) ? "暂未填写" : o.getBank_card());
                        SPUtil.putAndApply(context, "bank_name", TextUtils.isEmpty(o.getBank()) ? "暂未填写" : o.getBank());
                        SPUtil.putAndApply(context, "add_time", o.getAdd_time());
                        SPUtil.putAndApply(context, "edit_time", o.getEdit_time());
                        /**
                         * @see LoginActivity#showMessage(String)
                         */
//                        mView.showMessage(message);
                        /**
                         * @see LoginActivity#startShowView()
                         */
                        mView.startShowView();

                    }
                });


    }

    @Override
    public void https12306() {
      /*  _restApi.Https12306().enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                KLog.i("Evd","onResponse"+response.code());
                try {
                    KLog.i("Evd","onResponse"+response.body().string()+"-");
                }catch (Exception e){

                }

            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                KLog.i("Evd","onFailure"+t.getMessage());
            }
        });*/

        _restApi.testServer().enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                KLog.i("Evd","onResponse"+response.code());
                try {
                    KLog.i("Evd","onResponse"+response.body().string()+"-");
                }catch (Exception e){

                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                KLog.i("Evd","onFailure"+t.getMessage());

            }
        });
    }

    String msaage;

    class LoginResultFunc<T> extends HttpResultFunc<T> {
        @Override
        public T call(HttpResultBean<T> httpResult) {
            KLog.i("Evd", httpResult == null ? "1-" : "0-" + httpResult.getCode() + "-" + httpResult.getInfo() + "-" + httpResult.getData().toString());
            if (httpResult.getCode() == 2) {
                throw new Api2Exception(httpResult.getInfo());
            }
            message = httpResult.getInfo();
            return httpResult.getData();
        }
    }
}
